package httputil

import (
	"encoding/json"
	"github.com/duke-git/lancet/v2/netutil"
	"io"
)

func PostJsonWithHeader(url string, header map[string]string, reqData any, rspData any) error {
	bodyParams, _ := json.Marshal(reqData)
	resp, err := netutil.HttpPost(url, header, nil, bodyParams)
	if err != nil {
		return err
	}
	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	err = json.Unmarshal(bytes, rspData)
	return err
}

func HttpPostJsonWithHeader(url string, params interface{}, header map[string]string) ([]byte, error) {
	bodyParams, _ := json.Marshal(params)
	resp, err := netutil.HttpPost(url, header, nil, bodyParams)
	if err != nil {
		return nil, err
	}
	body, err := io.ReadAll(resp.Body)
	return body, err
}

func HttpPostJson(url string, params interface{}) ([]byte, error) {
	header := map[string]string{
		ContentType: ApplicationJson,
	}
	return HttpPostJsonWithHeader(url, params, header)
}

func HttpGetJsonWithHeader(url string, header map[string]string) ([]byte, error) {
	resp, err := netutil.HttpGet(url, header, nil)
	if err != nil {
		return nil, err
	}
	body, err := io.ReadAll(resp.Body)
	return body, err
}

func HttpGetJson(url string) ([]byte, error) {
	header := map[string]string{
		ContentType: ApplicationJson,
	}
	return HttpGetJsonWithHeader(url, header)
}

var JsonHeader = map[string]string{
	ContentType: ApplicationJson,
}
